<template>
  <!-- 查询条件 -->
  <div style="font-size: larger;">
    栋舍类型：
     <el-select style="width: 220px" v-model="page.cottageTypeId" placeholder="请选择栋舍类型" clearable >
        <el-option v-for="item in cottageTypes"  :label="item.cottageTypeName" :value="item.cottageTypeId" />
      </el-select>
    &emsp;栋舍名称：<el-input v-model="page.cottageName" style="width: 220px"></el-input>&emsp;
    负责人：<el-select style="width: 220px" v-model="page.persId" placeholder="请选择负责人"clearable >
      <el-option v-for="item in employees"  :label="item.firstName" :value="item.employeeId" />
    </el-select>
    &emsp;<el-button type="danger" :icon="Search" @click="getCottagesDatas()" >查询</el-button>
    <br><br>
    <el-button :icon="Plus" type="danger" @click="dialogFormVisible = true">新增</el-button>
    <el-button type="danger" @click="allDeleteCottage()" :icon="Delete"  >批量删除</el-button>
  </div>
  <br>

  <!-- 列表显示 -->
  <el-table
    :data="tableData"
    border
    style="width: 100%"
    @selection-change="handleSelectionChange"
    :header-cell-style="{ height: '100px', fontSize: '15px',color:'black' , backgroundColor: 'antiquewhite' }"
  >
    <el-table-column type="selection" width="55" />
    <el-table-column prop="cottagesId" label="序号" />
    <el-table-column prop="cottageTypeName" label="栋舍类型" width="100" />
    <el-table-column prop="cottageName" label="栋舍名称" width="100" />
    <el-table-column prop="persName" label="负责人" />
    <el-table-column prop="productionName" label="生产人员" width="100" />
    <el-table-column prop="status" label="状态" >
      <template v-slot="scope" >
        <el-tag type="success" v-if="!scope.row.status" >启用</el-tag>
        <el-tag type="danger" v-else >禁用</el-tag>
      </template>
    </el-table-column>
    <el-table-column prop="createName" label="创建人" />
    <el-table-column prop="createTime" label="创建时间"width=200  >
       <template v-slot="scope" >
        {{ scope.row.createTime.substring(0,19).replace("T"," ") }}
      </template>
    </el-table-column>
    <el-table-column prop="updateName" label="修改人" />
    <el-table-column prop="updateTime" label="修改时间" width=200  >
      <template v-slot="scope" >
        {{ scope.row.updateTime==null? "":scope.row.updateTime.substring(0,19).replace("T"," ") }}
      </template>
    </el-table-column>
    <el-table-column label="操作" width="180" >
       <template v-slot="scope" >
        <el-button type="primary" :icon="Edit" circle  @click="detailCottage(scope.row.cottagesId)"/>
        <el-button type="danger" :icon="Delete" circle @click="deleteCottage(scope.row.cottagesId)" />&nbsp;
        <el-link type="success" :icon="Setting" @click="getFieids(scope.row)"  >栏位管理</el-link>
      </template>
    </el-table-column>
  </el-table>
<el-pagination
      v-model:current-page="page.pageIndex"
      v-model:page-size="page.pageSize"
      :page-sizes="[5, 10, 15, 20]"
      :background="true"
      layout="total, sizes, prev, pager, next, jumper"
      :total="page.totalCount"
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
    />
  <!-- 对话框新增 -->
  <el-dialog v-model="dialogFormVisible" title="栋舍新增" width="500" >
    <el-form
      ref="ruleFormRef"
      style="max-width: 600px"
    
      :model="ruleForm"
      :rules="rules"
      label-width="auto"
      :size="formSize"
      status-icon
       class="myDialogClass"
    >
      <el-form-item el-form-item label="栋舍类型" prop="cottageTypeId">
        <el-select v-model="ruleForm.cottageTypeId" placeholder="请选择栋舍类型"style="margin-top: 8px;"clearable>
          <el-option v-for="item in cottageTypes"  :label="item.cottageTypeName" :value="item.cottageTypeId" />
        </el-select>
      </el-form-item>
      <el-form-item label="栋舍名称" prop="cottageName">
        <el-input v-model="ruleForm.cottageName" placeholder="请输入栋舍名称" />
      </el-form-item>
      <el-form-item label="负责人" prop="persId">
        <el-select v-model="ruleForm.persId" placeholder="请选择负责人"clearable>
          <el-option v-for="item in employees"  :label="item.firstName" :value="item.employeeId" />
        </el-select>
        <br />
        <span>注：用于以负责人维度汇总栋舍绩效使用。</span>
      </el-form-item>
      <el-form-item label="生产人员" prop="production">
         <el-select v-model="ruleForm.production" placeholder="请选择生产人员"clearable>
          <el-option v-for="item in employees"  :label="item.firstName" :value="item.employeeId" />
        </el-select>
        <br />
        <span  style="color: red">注：用于移动端查看我管理的栋舍使用。</span>
      </el-form-item>
      <el-form-item label="状态"  prop="status" >
        <el-radio-group v-model="ruleForm.status">
          <el-radio :value="false">启用</el-radio>
          <el-radio :value="true">禁用</el-radio>
        </el-radio-group>
      </el-form-item>
      <el-form-item label="备注" prop="remark" >
        <el-input style="margin-bottom: 8px;"
          type="textarea"
          placeholder="请输入备注"
          v-model="ruleForm.remark"
        ></el-input>
      </el-form-item>
    </el-form>
    <template #footer>
      <div class="dialog-footer">
         <el-button type="primary"  @click="resetForm(ruleFormRef)">清空</el-button>
        <el-button type="primary" @click="dialogFormVisible = false">返回</el-button>
        <el-button type="primary" @click="submitForm(ruleFormRef)">
          保存
        </el-button>
      </div>
    </template>
  </el-dialog>


    <!-- 对话框修改 -->
  <el-dialog v-model="dialogFormVisible1" title="栋舍新增" width="500" >
    <el-form
      ref="ruleFormRef"
      style="max-width: 600px"
    
      :model="ruleForm1"
      :rules="rules"
      label-width="auto"
      :size="formSize"
      status-icon
    >
      <el-form-item el-form-item label="栋舍类型" prop="cottageTypeId">
        <el-select v-model="ruleForm1.cottageTypeId" placeholder="请选择栋舍类型"style="margin-top: 8px;"clearable>
          <el-option v-for="item in cottageTypes"  :label="item.cottageTypeName" :value="item.cottageTypeId" />
        </el-select>
      </el-form-item>
      <el-form-item label="栋舍名称" prop="cottageName">
        <el-input v-model="ruleForm1.cottageName" placeholder="请输入栋舍名称" />
      </el-form-item>
      <el-form-item label="负责人" prop="persId">
        <el-select v-model="ruleForm1.persId" placeholder="请选择负责人"clearable>
          <el-option v-for="item in employees"  :label="item.firstName" :value="item.employeeId" />
        </el-select>
        <br />
        <span>注：用于以负责人维度汇总栋舍绩效使用。</span>
      </el-form-item>
      <el-form-item label="生产人员" prop="production"  >
         <el-select v-model="ruleForm1.production" placeholder="请选择生产人员"clearable>
          <el-option v-for="item in employees"  :label="item.firstName" :value="item.employeeId" />
        </el-select>
        <br />
        <span  style="color: red">注：用于移动端查看我管理的栋舍使用。</span>
      </el-form-item>
      <el-form-item label="状态"  prop="status" >
        <el-radio-group v-model="ruleForm1.status">
          <el-radio :value="false">启用</el-radio>
          <el-radio :value="true">禁用</el-radio>
        </el-radio-group>
      </el-form-item>
      <el-form-item label="备注" prop="remark" >
        <el-input style="margin-bottom: 8px;"
          type="textarea"
          placeholder="请输入备注"
          v-model="ruleForm1.remark"
        ></el-input>
      </el-form-item>
    </el-form>
    <template #footer>
      <div class="dialog-footer">
         <el-button type="primary" @click="resetForm(ruleFormRef)">清空</el-button>
        <el-button type="primary" @click="dialogFormVisible1 = false">返回</el-button>
        <el-button type="primary" @click="submitForm1(ruleFormRef)">
          保存
        </el-button>
      </div>
    </template>
  </el-dialog>




  <!-- 栏位管理 -->
  <el-dialog v-model="Columns" title="栏位管理" width="1000px">
    当前栋舍：<input v-model=" fieidpage.cottageName" disabled ></input>&emsp;
    <el-button :icon="Plus" type="danger"  @click="AddColumns = true">新增栏位</el-button>
    
    <el-table :data="fieidDatas" style="width: 100%">
      <el-table-column prop="fieIdId" label="序号" />
      <el-table-column prop="fieIdName" label="栏位名称" />
      <!-- <el-table-column label="操作" /> -->
      
    </el-table>
    <el-pagination
        v-model:current-page="fieidpage.pageIndex"
        v-model:page-size="fieidpage.pageSize"
        :page-sizes="[5, 10, 15, 20]"
        :background="true"
        layout="total, sizes, prev, pager, next, jumper"
        :total="fieidpage.totalCount"
        @size-change="handleSizeChange1"
        @current-change="handleCurrentChange1"
      />
  </el-dialog>

  <!-- 新增栏位 fiedldForm-->
  <el-dialog v-model="AddColumns" title="新增栏位" width="500">
    <el-form
      ref="ruleFormRef"
      style="max-width: 600px"
      :model="fiedldForm"
      :rules="rules"
      label-width="auto"
      class="demo-ruleForm"
      :size="formSize"
      status-icon
      
    >
      <el-form-item label="添加方式">
        <el-radio-group v-model="AddColumns1">
          <el-radio :value="true">单个新增</el-radio>
          <el-radio :value="false">批量新增</el-radio>
        </el-radio-group>
      </el-form-item>
      <el-form-item label="当前栋舍">  <el-input type="text"  v-model=" fieidpage.cottageName" disabled /> </el-form-item>
      
        <el-form-item label="栏位名称" v-if="AddColumns1" prop="fieIdName">
        <el-input v-model="fiedldForm.fieIdName" placeholder="请输入栏位名称" />
      </el-form-item>
      

      
        <el-form-item label="前缀" prop="prefix"  v-if="!AddColumns1" >
        <el-input v-model="fiedldForm.prefix" placeholder="请输入前缀" />
      </el-form-item>
      <el-form-item label="开始编号" prop="fieldNumber"v-if="!AddColumns1" >
        <el-input v-model="fiedldForm.fieldNumber" placeholder="请输入开始编号" />
      </el-form-item>
      <el-form-item label="栏位数量" prop="getNumber"v-if="!AddColumns1">
        <el-input v-model="fiedldForm.getNumber" placeholder="请输入栏位数量" />
      </el-form-item>
      <el-form-item label="生成栏位"v-if="!AddColumns1">
        {{getStartAdnEnd[2]==0?'--':getStartAdnEnd[0]}}至{{getStartAdnEnd[2]==0?'--':getStartAdnEnd[1] }}
      </el-form-item>
     
    </el-form>
    <template #footer>
      <div class="dialog-footer">
        <el-button :icon="SuccessFilled" type="primary" @click="submitForm2(ruleFormRef)">
          保存
        </el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script setup lang="ts">
import { reactive, ref, onMounted, computed } from 'vue';
import axios from 'axios';
import { useRoute, useRouter } from 'vue-router';
import { ElMessage, ElMessageBox } from 'element-plus';
import type { ComponentSize, FormInstance, FormRules } from 'element-plus';
import {
  Delete,
  Edit,
  Search,
  Plus,
  Setting,
  SuccessFilled,
} from '@element-plus/icons-vue'
//调用持久化
import { useCounterStore } from '@/stores/counter';
const counterStore = useCounterStore();
const route = useRoute();
const router = useRouter();

const multipleSelection:any = ref([]);

const handleSelectionChange = (val: any) => {
  multipleSelection.value = val;
  console.log(multipleSelection.value)
};

const page = reactive({
  pageIndex: 1,
  pageSize: 5,
  cottageTypeId: '',
  cottageName: '',
  persId:'',
  totalCount: 0,
  totalPage: 0
});

//分页相关
const handleSizeChange = (val: any) => {
  page.pageSize = val;
  getCottagesDatas();
};

const handleCurrentChange = (val: any) => {
  page.pageIndex = val;
  getCottagesDatas();
};
const dialogFormVisible = ref(false);
const Columns = ref(false);
const AddColumns = ref(false);
const AddColumns1 = ref(true);
const AddColumns2 = ref(!AddColumns1);

//添加栋舍信息
const ruleForm = reactive({
  farmId: 1,
  cottageTypeId:'',
  cottageName: '',
  persId: '',
  production: '',
  status:'',
  remark:'',
  createId:1
});

const radiotype = ref('1');

const formSize = ref<ComponentSize>('default');
const ruleFormRef = ref<FormInstance>();

const rules = reactive<FormRules>({
  cottageTypeId: [{ required: true, message: '栋舍类型未选择', trigger: 'change' }],
  cottageName: [{ required: true, message: '栋舍名称不能为空', trigger: 'blur' }],
  persId: [{ required: true, message: '负责人不能为空', trigger: 'change' }],
  production: [{ required: true, message: '生产人员不能为空', trigger: 'change' }],
  remark: [{ required: true, message: '备注不能为空', trigger: 'blur' }],
  status: [{ required: true, message: '状态未选择', trigger: 'change' }],
  fieIdName: [{ required: true, message: '围栏名称不能为空', trigger: 'blur' }],
  prefix: [{ required: true, message: '前缀不能为空', trigger: 'blur' }],
  fieldNumber: [{ required: true, message: '开始编号不能为空', trigger: 'blur' }],
  getNumber: [{ required: true, message: '数量不能为空', trigger: 'blur' }],
});

//添加栋舍
const submitForm = async (formEl: FormInstance | undefined) => {
  if (!formEl) return;
  await formEl.validate((valid, fields) => {
    if (valid) {
      axios.post("http://localhost:5039/api/Cottages/CreateCottage", ruleForm).then(res => {
        if (res.data.code > 0) {
          ElMessage.success("栋舍信息添加成功");
          resetForm(formEl);
          // ruleForm.cottageTypeId = ''
          // ruleForm.cottageName=''
          // ruleForm.persId = ''
          // ruleForm.production = ''
          // ruleForm.remark = ''
          // ruleForm.status=''
           dialogFormVisible.value = false;
          getCottagesDatas()
        } else {
          ElMessage.error("添加栋舍失败了，再试试...")
          return;
        }
      })
    } else {
      console.log('error submit!', fields);
    }
  });
};
//清空
const resetForm = (formEl: FormInstance | undefined) => {
  if (!formEl) return
  formEl.resetFields()
}

onMounted(() => {
  getCottageTypesData();
  getEmployeeData();
  getCottagesDatas();
  
})

//栋舍分类信息
const cottageTypes:any = ref([])
const getCottageTypesData = () => {
  axios.post("http://localhost:5039/api/Cottages/SearchCottageTypes",{}).then(res => {
    // console.log(res.data)
    cottageTypes.value=res.data.data
  })
}

//负责人（生产人）信息
const employees:any = ref([])
const getEmployeeData = () => {
  axios.post("http://localhost:5039/api/Cottages/SearchEmployees",{}).then(res => {
    // console.log(res.data)
    employees.value=res.data.data
  })
}




//栋舍信息查询显示（分页）
const tableData = ref([]);
const getCottagesDatas = () => {
  var request:any = ref({})
  request.pageSize = page.pageSize;
  request.pageIndex = page.pageIndex;
  request.cottageName = page.cottageName;
  request.persId = page.persId||0;
  request.cottageTypeId = page.cottageTypeId||0
  axios.post("http://localhost:5039/api/Cottages/CottageList",request).then(res => {
    console.log(res.data)
    tableData.value = res.data.data
    page.totalCount = res.data.totalCount
    page.totalPage =res.data.totalPage
  })
}

//栋舍信息删除（批量）

const allDeleteCottage = () => {

  var request: any = ref({})

  let idsArry: any = [];
  if (multipleSelection.value.length < 1) {
    ElMessage.error("一项都没选");
    return;
  }
  multipleSelection.value.forEach((c:any) => {
    idsArry.push(c.cottagesId)
  });
  

request.ids = idsArry.toString()
console.log(request)
   ElMessageBox.confirm(
    '确认删除吗?',
    '警告',
    {
      confirmButtonText: '确认',
      cancelButtonText: '取消',
      type: 'warning',
    }
  )
    .then(() => {
      axios.delete("http://localhost:5039/api/Cottages/AllDeleteCottages",{
         data: request,
        headers: {
       'Content-Type': 'application/problem+json;charset=UTF-8'
     }
       } ).then(res => {
    if (res.data.code > 0) {
      ElMessage.success("删除成功");
      getCottagesDatas();
    } else {
      ElMessage.error("删除失败，再试试...");
      return;
    }
  })
    })
    .catch(() => {
      ElMessage({
        type: 'info',
        message: '取消操作',
      })
    })

  
}
//栋舍信息删除
const deleteCottage = (cottagesId: number) => {
  var request: any = ref({})
  request.ids = cottagesId.toString();
  ElMessageBox.confirm(
    '确认删除吗?',
    '警告',
    {
      confirmButtonText: '确认',
      cancelButtonText: '取消',
      type: 'warning',
    }
  )
    .then(() => {
      axios.delete("http://localhost:5039/api/Cottages/AllDeleteCottages",{
         data: request,
        headers: {
       'Content-Type': 'application/problem+json;charset=UTF-8'
     }
       } ).then(res => {
    if (res.data.code > 0) {
      ElMessage.success("删除成功");
      getCottagesDatas();
    } else {
      ElMessage.error("删除失败，再试试...");
      return;
    }
  })
    })
    .catch(() => {
      ElMessage({
        type: 'info',
        message: '取消操作',
      })
    })
}

//修改栋舍数据
const ruleForm1 = reactive({
  cottagesId:'',
  farmId: 1,
  cottageTypeId:'',
  cottageName: '',
  persId: '',
  production: '',
  status:'',
  remark:'',
  createId: 1,
  createTime: '',
  updateId:1
});
const dialogFormVisible1=ref(false)
//反添栋舍信息
const detailCottage = (cottagesId: number) => {
  dialogFormVisible1.value=true
  var request: any = ref({})
  request.cottagesId = cottagesId
  axios.post("http://localhost:5039/api/Cottages/DetailCottage", request).then(res => {
    ruleForm1.cottagesId=res.data.item.cottagesId
    ruleForm1.farmId = res.data.item.farmId
    ruleForm1.cottageTypeId = res.data.item.cottageTypeId
    ruleForm1.cottageName = res.data.item.cottageName
    ruleForm1.persId = res.data.item.persId
    ruleForm1.production = res.data.item.production
    ruleForm1.status = res.data.item.status
    ruleForm1.remark = res.data.item.remark
    ruleForm1.createId = res.data.item.createId
    ruleForm1.createTime = res.data.item.createTime
  })
}
//修改栋舍信息
const submitForm1 = async (formEl: FormInstance | undefined) => {
  if (!formEl) return;
  await formEl.validate((valid, fields) => {
    if (valid) {
      axios.put("http://localhost:5039/api/Cottages/UpdateCottage", ruleForm1).then(res => {
        if (res.data.code > 0) {
          ElMessage.success("栋舍信息修改成功");
          dialogFormVisible1.value = false;
          getCottagesDatas()
        } else {
          ElMessage.error("修改栋舍失败了，再试试...")
          return;
        }
      })
    } else {
      console.log('error submit!', fields);
    }
  });
};


const fieidpage = reactive({
  cottagesId:'',
  pageIndex: 1,
  pageSize: 5,
  totalCount: 0,
  totalPage: 0,
  cottageName:''
});

//栏位信息分页显示
const fieidDatas: any = ref([]);

const getFieids = (row:any) => {
  Columns.value = true;
  fieidpage.cottageName = row.cottageName
  fieidpage.cottagesId = row.cottagesId
  fiedldForm.cottagesId= row.cottagesId
 getFields()
}

const getFields = () => {
  
   axios.post("http://localhost:5039/api/Cottages/SearchFields", fieidpage).then(res => {
    fieidDatas.value = res.data.data
    fieidpage.totalCount = res.data.totalCount
    fieidpage.totalPage = res.data.totalPage
  })
}



//分页相关
const handleSizeChange1 = (val: any) => {
  fieidpage.pageSize = val;
  getFields();
};

const handleCurrentChange1 = (val: any) => {
  fieidpage.pageIndex = val;
  getFields();
};

//添加栏信息
const fiedldForm = reactive({
  fieIdName: '',
  cottagesId: '',
  prefix: '',
  fieldNumber: '',
  getNumber:''
})

//计算属性
const getStartAdnEnd = computed(() => {
  var index = Number(fiedldForm.fieldNumber) 
  var names = fiedldForm.prefix.toString();
  var sumNumber =Number(fiedldForm.getNumber) 
  return [names+index.toString(),names+(sumNumber+index-1).toString(),sumNumber]

})
//添加方法

const submitForm2 = async (formEl: FormInstance | undefined) => {
  if (!formEl) return;
  await formEl.validate((valid, fields) => {
    if (valid) {
      let request:any = ref({})
      request.fieIdName = fiedldForm.fieIdName
      request.cottageId = fiedldForm.cottagesId
      request.prefix = fiedldForm.prefix
      request.fieldNumber = Number(fiedldForm.fieldNumber)
      request.getNumber = Number(fiedldForm.getNumber) 
      console.log(request)
      axios.post("http://localhost:5039/api/Cottages/CreateFields", request).then(res => {
    console.log(res.data)
    if (res.data.code > 0) {
      ElMessage.success(res.data.messege);

      
    } else {
      ElMessage.error(res.data.messege);
        }
        fiedldForm.fieldNumber = '';
        fiedldForm.getNumber = '';
        fiedldForm.prefix=''
        AddColumns.value = false;
        getFields();
  })
    } else {
      console.log('error submit!', fields);
    }
  });
};


</script>




<style scoped>



</style>

